package cn.iocoder.yudao.module.member.controller.app.user;

import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.framework.ip.core.utils.IPUtils;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.AppAuthLoginRespVO;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.AppAuthScanLoginRespVO;
import cn.iocoder.yudao.module.member.controller.app.user.vo.*;
import cn.iocoder.yudao.module.member.convert.user.MemberUserConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.level.MemberLevelDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.level.MemberLevelService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.mp.api.qrcode.TempQrcodeApi;
import cn.iocoder.yudao.module.mp.enums.qrcode.MpQrSceneEnum;
import cn.iocoder.yudao.module.system.api.logger.LoginLogApi;
import cn.iocoder.yudao.module.system.api.logger.dto.LoginLogRespDTO;
import cn.iocoder.yudao.module.system.api.social.SocialUserApi;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 用户个人中心")
@RestController
@RequestMapping("/member/user")
@Validated
@Slf4j
public class AppMemberUserController {

    @Resource
    private MemberUserService userService;
    @Resource
    private MemberLevelService levelService;
    @Resource
    private TempQrcodeApi tempQrcodeApi;
    @Value("${wx.mp.app-id}")
    private String wxMpAppId;
    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private LoginLogApi loginLogApi;

    @GetMapping("/get")
    @Operation(summary = "获得基本信息")
    public CommonResult<AppMemberUserInfoRespVO> getUserInfo() {
        MemberUserDO user = userService.getUser(getLoginUserId());
        MemberLevelDO level = levelService.getLevel(user.getLevelId());
        SocialUserRespDTO socialUser = socialUserApi.getSocialUserByUserId(UserTypeEnum.MEMBER.getValue(), getLoginUserId(), SocialTypeEnum.WECHAT_MP.getType());
        AppMemberUserInfoRespVO userInfoRespVO = MemberUserConvert.INSTANCE.convert(user, level);
        userInfoRespVO.setBindWechat(socialUser != null && socialUser.getOpenid() != null);
        return success(userInfoRespVO);
    }

    @PutMapping("/update")
    @Operation(summary = "修改基本信息")
    public CommonResult<Boolean> updateUser(@RequestBody @Valid AppMemberUserUpdateReqVO reqVO) {
        userService.updateUser(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-mobile")
    @Operation(summary = "修改用户手机")
    public CommonResult<Boolean> updateUserMobile(@RequestBody @Valid AppMemberUserUpdateMobileReqVO reqVO) {
        userService.updateUserMobile(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-mobile-by-weixin")
    @Operation(summary = "基于微信小程序的授权码，修改用户手机")
    public CommonResult<Boolean> updateUserMobileByWeixin(@RequestBody @Valid AppMemberUserUpdateMobileByWeixinReqVO reqVO) {
        userService.updateUserMobileByWeixin(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(summary = "修改用户密码", description = "用户修改密码时使用")
    public CommonResult<Boolean> updateUserPassword(@RequestBody @Valid AppMemberUserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/complete-info")
    @Operation(summary = "补充用户信息", description = "用户注册后补充信息时使用")
    public CommonResult<Boolean> addUserPassword(@RequestBody @Valid AppMemberUserCompleteInfoReqVO reqVO) {
        userService.completeUserInfo(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/reset-password")
    @Operation(summary = "重置密码", description = "用户忘记密码时使用")
    @PermitAll
    public CommonResult<Boolean> resetUserPassword(@RequestBody @Valid AppMemberUserResetPasswordReqVO reqVO) {
        userService.resetUserPassword(reqVO);
        return success(true);
    }

    @GetMapping("/get-weixin-bind-qr")
    @Operation(summary = "微信绑定获取二维码")
    @PermitAll
    public CommonResult<WxMpQrCodeTicket> getWeixinLoginQr() {
        return success(tempQrcodeApi.genTempQrCode(wxMpAppId, MpQrSceneEnum.BIND));
    }

    @GetMapping("/check-weixin-bind-qr-scan")
    @Operation(summary = "检查微信绑定二维码扫码结果")
    @PermitAll
    public CommonResult<AppAuthLoginRespVO> weixinQrLogin(@RequestParam String ticket) {
        AppAuthScanLoginRespVO scanLoginRespVO = new AppAuthScanLoginRespVO();
        String scannerOpenid = tempQrcodeApi.getTempQrCodeScanOpenid(ticket);
        if (!StringUtils.hasLength(scannerOpenid)) {
            scanLoginRespVO.setScanned(true);
            socialUserApi.bindSocialUser(UserTypeEnum.MEMBER.getValue(), getLoginUserId(), SocialTypeEnum.WECHAT_MP.getType(), scannerOpenid);
        }
        return success(scanLoginRespVO);
    }

    @GetMapping("/login-record")
    @Operation(summary = "获得会员登录记录分页")
    public CommonResult<PageResult<AppLoginLogPageRespVO>> getCompanyTemplatePage(@Valid AppLoginLogPageReqVO pageReqVO) {
        PageResult<LoginLogRespDTO> loginLogPage = loginLogApi.getLoginLogPage(getLoginUserId(), pageReqVO.getPageNo(), pageReqVO.getPageSize());
        PageResult<AppLoginLogPageRespVO> result = new PageResult<>();
        result.setTotal(loginLogPage.getTotal());
        List<Long> userIds = new ArrayList<>();
        loginLogPage.getList().forEach(item -> {
            if (item.getUserId() != null && !userIds.contains(item.getUserId())) {
                userIds.add(item.getUserId());
            }
        });
        Map<Long, MemberUserDO> userDOMap = userService.getUserList(userIds).stream().collect(Collectors.toMap(MemberUserDO::getId, user -> user));
        List<AppLoginLogPageRespVO> list = loginLogPage.getList().stream().map(item -> {
            AppLoginLogPageRespVO respVO = new AppLoginLogPageRespVO();
            respVO.setNickname(userDOMap.get(item.getUserId()).getNickname());
            respVO.setMobile(userDOMap.get(item.getUserId()).getMobile());
            String userIp = item.getUserIp();
            respVO.setUserIp(userIp);
            Integer areaId = IPUtils.getAreaId(userIp);
            if (areaId > 0) {
                respVO.setAddress(AreaUtils.format(areaId, "-"));
            } else {
                respVO.setAddress("-");
            }
            respVO.setCreateTime(item.getCreateTime());
            return respVO;
        }).toList();
        result.setList(list);
        return success(result);
    }
}
